#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org
# Copyright (C) 2019 X-WRT <dev@x-wrt.com>

START=96

MOUNT_NTFS="mount.ntfs-3g -o noatime,async,iocharset=utf8,uid=1000,gid=1000,fmask=0000,dmask=0000,rw,big_writes"
MOUNT_CMD1="mount -o noatime,async,iocharset=utf8,uid=1000,gid=1000,fmask=0000,dmask=0000,rw"
MOUNT_CMD2="mount -o noatime,async,rw"
MOUNT_CMD3="mount -o rw"
MOUNT_CMD4="mount"

#try_mount "$1" "$2"
try_mount()
{
	$MOUNT_NTFS "$1" "$2" && return 0
	$MOUNT_CMD1 "$1" "$2" && return 0
	$MOUNT_CMD2 "$1" "$2" && return 0
	$MOUNT_CMD3 "$1" "$2" && return 0
	$MOUNT_CMD4 "$1" "$2" && return 0
	return 1
}

auto_mount_boot()
{
	for i in `seq 1 300`; do
		mount | grep overlayfs | grep 'workdir=/overlay/work' >/dev/null  2>&1
		test $? -eq 0 && break
		sleep 2
	done

	diskdev=sda
	. /lib/upgrade/common.sh
	export_bootdevice && export_partdevice diskdev 0
	diskdev=/dev/$diskdev

	for DEV in `ls /dev/sd*[0-9]* 2>/dev/null`; do
		[ x$DEV = x`mount | grep "$DEV " | awk '{print $1}'` ] && continue

		test -f /rom/etc/sda.ready && {
			echo $DEV | grep -q $diskdev && continue
		}

		ddir=/mnt/`basename $DEV`
		mkdir -p "$ddir" || continue
		if try_mount "$DEV" "$ddir"; then
			logger -t "auto_usb_mount" "boot auto mount $DEV to $ddir success!"
		else
			logger -t "auto_usb_mount" "boot mount $DEV to $ddir failed!"
		fi
	done
	test -e /etc/hotplug.d/block/20-auto_usb_mount || {
		mkdir -p /etc/hotplug.d/block
		ln -sf /usr/share/base-config-setting/auto_usb_mount.hotplug /etc/hotplug.d/block/20-auto_usb_mount
	}
	uci get fstab.@global[0].anon_mount_bak 2>/dev/null && {
		uci set fstab.@global[0].anon_mount="`uci get fstab.@global[0].anon_mount_bak`"
		uci delete fstab.@global[0].anon_mount_bak
		uci commit fstab
	}
}

boot() {
	auto_mount_boot &
}
